package com.xiaowu.house.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowu.house.appuser.domain.dto.AppUserDTO;
import com.xiaowu.house.appuser.domain.dto.AppUserListReqDTO;
import com.xiaowu.house.appuser.domain.dto.UserEditReqDTO;
import com.xiaowu.house.domain.ResultCode;
import com.xiaowu.house.domain.dto.BasePageDTO;
import com.xiaowu.house.exception.ServiceException;
import com.xiaowu.house.user.config.RabbitConfig;
import com.xiaowu.house.user.domain.entity.AppUser;
import com.xiaowu.house.user.domain.entity.SysUser;
import com.xiaowu.house.user.mapper.AppUserMapper;
import com.xiaowu.house.user.service.IAppUserService;
import com.xiaowu.house.utils.AESUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@Slf4j
@Service
public class AppUserServiceImpl implements IAppUserService {

    @Autowired
    private AppUserMapper appUserMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${appuser.info.defaultAvatar}")
    private String defaultAvatar;


    @Override
    public AppUserDTO registerByOpenId(String openId) {
        if (StringUtils.isEmpty(openId)) {
            throw new ServiceException(ResultCode.INVALID_PARA.getCode(), "微信ID不能为空");
        }
        AppUser appUser = new AppUser();
        appUser.setOpenId(openId);
        appUser.setNickName("用户"+ (int) (Math.random() * 9000) + 1000);
        appUser.setAvatar(defaultAvatar);
        appUserMapper.insert(appUser);
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser, appUserDTO);
        appUserDTO.setUserId(appUser.getId());
        return appUserDTO;
    }

    @Override
    public AppUserDTO findByOpenId(String openId) {
        if (StringUtils.isEmpty(openId)) {
            return null;
        }

        AppUser appUser = appUserMapper
                .selectOne(new LambdaQueryWrapper<AppUser>().eq(AppUser::getOpenId, openId));

        if (appUser == null) {
            return null;
        }
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser, appUserDTO);

        appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUser.getPhoneNumber()));
        return appUserDTO;
    }

    @Override
    public AppUserDTO findByPhone(String phoneNumber) {
        if (StringUtils.isEmpty(phoneNumber)) {
            return null;
        }

        AppUser appUser = appUserMapper
                .selectOne(new LambdaQueryWrapper<AppUser>()
                        .eq(AppUser::getPhoneNumber, AESUtil.encryptHex(phoneNumber)));

        if (appUser == null) {
            return null;
        }

        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser, appUserDTO);
        appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUser.getPhoneNumber()));
        appUserDTO.setUserId(appUser.getId());
        return appUserDTO;
    }

    @Override
    public AppUserDTO registerByPhone(String phoneNumber) {
        if (StringUtils.isEmpty(phoneNumber)) {
            throw new ServiceException(ResultCode.INVALID_PARA.getCode(), "手机号不能为空");
        }
        AppUser appUser = new AppUser();
        appUser.setPhoneNumber(AESUtil.encryptHex(phoneNumber));
        appUser.setNickName("用户"+ (int) (Math.random() * 9000) + 1000);
        appUser.setAvatar(defaultAvatar);
        appUserMapper.insert(appUser);
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser, appUserDTO);
        appUserDTO.setUserId(appUser.getId());
        return appUserDTO;
    }

    @Override
    public void edit(UserEditReqDTO userEditReqDTO) {
        AppUser appUser = appUserMapper.selectById(userEditReqDTO.getUserId());

        if (appUser == null) {
            throw new ServiceException(ResultCode.INVALID_PARA.getCode(), "用户不存在");
        }
        appUser.setNickName(userEditReqDTO.getNickName());
        appUser.setAvatar(userEditReqDTO.getAvtar());
        appUserMapper.updateById(appUser);

        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser, appUserDTO);
        appUserDTO.setUserId(appUser.getId());
        try {
            rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_NAME, "", appUserDTO);
        } catch (Exception exception) {
            log.error("编辑用户发送消息失败", exception);
        }
    }

    @Override
    public AppUserDTO findById(Long userId) {
        if (userId == null) {
            return null;
        }

        AppUser appUser = appUserMapper.selectById(userId);
        if (appUser == null) {
            return null;
        }
        AppUserDTO appUserDTO = new AppUserDTO();
        BeanUtils.copyProperties(appUser, appUserDTO);
        appUserDTO.setUserId(appUser.getId());
        appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUser.getPhoneNumber()));

        return appUserDTO;
    }

    @Override
    public List<AppUserDTO> list(List<Long> userIds) {
        if (userIds == null) {
            return Arrays.asList();
        }

        List<AppUser> appUsers = appUserMapper
                .selectList(new LambdaQueryWrapper<AppUser>()
                        .in(AppUser::getId, userIds));
        if (appUsers == null) {
            return Arrays.asList();
        }
        List<AppUserDTO> appUserDTOS = new ArrayList<>();

        appUserDTOS =  appUsers.stream().map(appUser -> {
            AppUserDTO appUserDTO = new AppUserDTO();
            BeanUtils.copyProperties(appUser, appUserDTO);
            appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUser.getPhoneNumber()));
            appUserDTO.setUserId(appUser.getId());
            return appUserDTO;
        }).collect(Collectors.toList());

        return appUserDTOS;
    }

    @Override
    public BasePageDTO<AppUserDTO> getUserList(AppUserListReqDTO appUserListReqDTO) {
        appUserListReqDTO.setPhoneNumber(AESUtil.encryptHex(appUserListReqDTO.getPhoneNumber()));
        BasePageDTO<AppUserDTO> result = new BasePageDTO();

        // 2 查询总数
        Long totals = appUserMapper.selectCount(appUserListReqDTO);
        if (totals == 0) {
            result.setTotals(0);
            result.setTotalPages(0);
            result.setList(new ArrayList<>());
            return result;
        }

        // 3 分页查询
        List<AppUser> appUserList = appUserMapper.selectPage(appUserListReqDTO);
        result.setTotals(totals.intValue());
        result.setTotalPages(
                BasePageDTO.calculateTotalPages(totals, appUserListReqDTO.getPageSize())
        );
        // 4 超页
        if (CollectionUtils.isEmpty(appUserList)) {
            result.setList(new ArrayList<>());
            return result;
        }
        // 5 对象列表结果转换
        result.setList(
                appUserList.stream()
                        .map(appUser -> {
                            AppUserDTO appUserDTO = new AppUserDTO();
                            BeanUtils.copyProperties(appUser, appUserDTO);
                            appUserDTO.setUserId(appUser.getId());
                            appUserDTO.setPhoneNumber(AESUtil.decryptHex(appUser.getPhoneNumber()));
                            return appUserDTO;
                        }).collect(Collectors.toList())
        );
        return result;
    }
}
